<script setup>
import {getCartList, deleteCart, updateCart} from "@/api/cart.js";
import {ref, computed} from "vue";
import {useCartStore} from "@/stores/cart.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {addToOrder, addToOrderDetail} from "@/api/order.js";
import {useOrderStore} from "@/stores/order.js";
import {useRouter} from "vue-router";


const router = useRouter();
//获取购物车列表 放入pinia
const cartStore = useCartStore();
const getCarts = async () => {
  const res = await getCartList();
  cartStore.cartList = res.data;
};
getCarts();

//判断是否全选
const allCheck = computed({
  get() {
    return cartStore.cartList.length > 0 && cartStore.cartList.every(item => item.selected);
  },
  set(value) {
    cartStore.cartList.forEach(item => {
      item.selected = value;
    });
  }
});

// 删除某个商品
const delCart = async (item) => {
  ElMessageBox.confirm(
      `确定要删除吗？`,
      "警告",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
  )
      .then(async () => {
        await deleteCart(item.flowerId);
        ElMessage.success("删除成功");
        await getCarts();
      })
      .catch(() => {
        ElMessage.info("已取消删除");
      });
};

//更新某个商品数量
const upCart = async (item) => {
  const res = await updateCart(item.flowerId, item.quantity);
};

const orderStore = useOrderStore();
//下单结算
const toCheckout = async () => {
  const totalAmount = cartStore.cartList
      .filter(item => item.selected)
      .reduce((sum, item) => sum + item.price * item.quantity, 0);
  
  if (totalAmount === 0) {
    ElMessage.error("请至少选择一件商品");
    return;
  }
  if(orderStore.orderDetailList.length!==0){
    ElMessage.error("有未支付的订单，请先支付");
    return;
  }
  const res1 = await addToOrder(totalAmount)
  
  const orderId = res1.data;
  const orderDetailList = cartStore.cartList
      .filter(item => item.selected === true) // 确保只筛选出选中的商品
      .map(item => ({
        orderId: orderId, // 确保 orderId 已正确赋值
        flowerId: item.flowerId,
        price: item.price,
        quantity: item.quantity,
        imageUrl: item.imageUrl,
        name: item.name,
      }));
  const res2 = await addToOrderDetail(orderDetailList);
  ElMessage.success("下单成功");
  
  orderStore.totalAmount = totalAmount;
  orderStore.orderId = orderId;
  orderStore.orderDetailList = orderDetailList;
  orderStore.createTime = Math.floor(Date.now() / 1000); // 存储为时间戳
  await getCarts();
  router.push("/checkout");
};

</script>

<template>
<div class="baseBox">
  <div class="container m-top-20">
    <div class="cart">
      <table>
        <thead>
          <tr>
            <th style="width: 120px">
              <el-checkbox v-model="allCheck" @change="allCheck"/>
            </th>
            <th style="width: 400px">商品信息</th>
            <th style="width: 220px">单价</th>
            <th style="width: 180px">数量</th>
            <th style="width: 180px">小计</th>
            <th style="width: 140px">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="i in cartStore.cartList" :key="i.id">
            <td>
              <el-checkbox v-model="i.selected"/>
            </td>
            <td>
              <div class="goods">
                <img :src="i.imageUrl" alt=""/>
                <div>
                  <p class="name ellipsis" style="margin-left: 70px">
                    {{ i.name }}
                  </p>
                </div>
              </div>
            </td>
            <td class="tc">
              <p>&yen;{{ i.price }}</p>
            </td>
            <td class="tc">
              <el-input-number v-model="i.quantity" @change="upCart(i)"/>
            </td>
            <td class="tc">
              <p class="f16 red">&yen;{{ (i.price * i.quantity).toFixed(2) }}</p>
            </td>
            <td class="tc">
              <button @click="delCart(i)">删除</button>
            </td>
          </tr>
          <tr v-if="cartStore.cartList.length === 0">
            <td colspan="6">
              <div class="cart-none">
                <el-empty description="购物车列表为空">
                  <el-button type="primary" @click="$router.push('/')">随便逛逛</el-button>
                </el-empty>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="action">
      <div class="batch">
        共 {{ cartStore.cartList.length }} 件商品，已选择 {{ cartStore.cartList.filter(i => i.selected).length }} 件，商品合计：
        <span class="red">
            ¥ {{
            cartStore.cartList
                .filter(i => i.selected)
                .reduce((sum, i) => sum + i.price * i.quantity, 0)
                .toFixed(2)
          }}
          </span>
      </div>
      <div class="total">
        <el-button size="large" type="primary" @click="toCheckout">下单结算</el-button>
      </div>
    </div>
  </div>
</div>
</template>

<style scoped>
.baseBox {
  
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  width: 85%;
  margin: 20px auto;
}

.cart {
  background: #fff;
  color: #333;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.cart table {
  width: 100%;
  border-collapse: collapse;
}

.cart thead {
  background-color: #f8f8f8;
}

.cart th,
.cart td {
  padding: 16px 20px;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
  vertical-align: middle;
}

.cart th:first-child,
.cart td:first-child {
  text-align: left;
  padding-left: 30px;
}

.goods {
  display: flex;
  align-items: center;
}

.goods img {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  object-fit: cover;
  margin-right: 10px;
}

.goods .name {
  font-size: 16px;
  color: #333;
}

.cart tbody tr:hover {
  background-color: #fdfdfd;
}

.cart-none {
  text-align: center;
  padding: 100px 0;
  background: #fff;
}

/* 删除按钮样式 */
.tc button {
  padding: 6px 12px;
  background-color: #f44336; /* 红色背景 */
  color: #fff; /* 白色文字 */
  border: none; /* 去掉边框 */
  border-radius: 6px; /* 圆角 */
  font-size: 14px;
  cursor: pointer; /* 鼠标悬停时显示手型 */
  transition: all 0.3s ease; /* 添加过渡效果 */
}

.tc button:hover {
  background-color: #d32f2f; /* 悬停时更深的红色 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
  transform: scale(1.05); /* 悬停时放大 */
}

.red {
  color: #d33;
}

.f16 {
  font-size: 16px;
}

.action {
  display: flex;
  background: #fff;
  margin-top: 20px;
  height: 80px;
  align-items: center;
  font-size: 16px;
  justify-content: space-between;
  padding: 0 30px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.action .batch {
  color: #666;
}

.action .batch .red {
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}

.action .total .el-button {
  padding: 12px 30px;
  font-size: 16px;
}
</style>